package com.znjc.web.controller.device;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.znjc.common.annotation.Log;
import com.znjc.common.core.controller.BaseController;
import com.znjc.common.core.domain.AjaxResult;
import com.znjc.common.core.domain.entity.SysDept;
import com.znjc.common.core.page.TableDataInfo;
import com.znjc.common.enums.BusinessType;
import com.znjc.common.utils.StringUtils;
import com.znjc.common.utils.poi.ExcelUtil;
import com.znjc.device.domain.DeviceType;
import com.znjc.device.domain.IotDataCheck;
import com.znjc.device.domain.IotSerial;
import com.znjc.device.service.IDeviceTypeSerialRefService;
import com.znjc.device.service.IDeviceTypeService;
import com.znjc.device.service.IIotDataCheckService;
import com.znjc.device.service.IIotSerialService;
import com.znjc.device.websocket.WebSocketUsers;
import com.znjc.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 设备类别管理Controller
 *
 * @author zengpc
 * @date 2023-12-04
 */
@Slf4j
@RestController
@RequestMapping("/device/type")
public class DeviceTypeController extends BaseController {
    @Autowired
    private IDeviceTypeService deviceTypeService;
    @Autowired
    private ISysDeptService deptService;


    /**
     * 查询设备类别管理列表
     */
    @PreAuthorize("@ss.hasPermi('device:type:list')")
    @GetMapping("/list")
    public TableDataInfo list(DeviceType deviceType) {
        startPage();
        LambdaQueryWrapper<DeviceType> wrapper = getWrapper(deviceType);
        List<DeviceType> list = deviceTypeService.list(wrapper);
        return getDataTable(packList(list));
    }



    /**
     * 导出设备类别管理列表
     */
    @PreAuthorize("@ss.hasPermi('device:type:export')")
    @Log(title = "设备类别管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DeviceType deviceType) {
        LambdaQueryWrapper<DeviceType> wrapper = getWrapper(deviceType);
        List<DeviceType> list = deviceTypeService.list(wrapper);
        ExcelUtil<DeviceType> util = new ExcelUtil<DeviceType>(DeviceType.class);
        util.exportExcel(response, packList(list), "设备类别管理数据");
    }

    /**
     * 获取设备类别管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('device:type:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(deviceTypeService.getById(id));
    }

    /**
     * 新增设备类别管理
     */
    @PreAuthorize("@ss.hasPermi('device:type:add')")
    @Log(title = "设备类别管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DeviceType deviceType) {
        deviceType.setDeptId(getDeptId());
        //默认关闭采集
        deviceType.setGatherStatus("1");
        return toAjax(deviceTypeService.save(deviceType));
    }

    /**
     * 修改设备类别管理
     */
    @PreAuthorize("@ss.hasPermi('device:type:edit')")
    @Log(title = "设备类别管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DeviceType deviceType) {
        return toAjax(deviceTypeService.updateById(deviceType));
    }

    /**
     * 删除设备类别管理
     */
    @PreAuthorize("@ss.hasPermi('device:type:remove')")
    @Log(title = "设备类别管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        List<Long> idsToDelete = new ArrayList<Long>(Arrays.asList(ids));
        if(CollectionUtils.isEmpty(idsToDelete)){
            return success();
        }
        List<DeviceType> list = deviceTypeService.listByIds(idsToDelete);
        Boolean flag = deviceTypeService.removeByIds(idsToDelete);
        if(flag && CollectionUtils.isNotEmpty(list)){
            list.forEach(deviceType->{
                deviceTypeService.editGather(deviceType,"1");
            });
        }
        return toAjax(flag);
    }

    /**
     * 获取设备类别选择框列表
     */
    @GetMapping("/optionselect")
    public AjaxResult optionselect() {
        List<DeviceType> devices = deviceTypeService.list();
        return success(devices);
    }

    /**
     * 查询公共方法
     * @param entity
     * @return
     */
    private LambdaQueryWrapper getWrapper(DeviceType entity){
        LambdaQueryWrapper<DeviceType> wrapper = new LambdaQueryWrapper<>();
        if (null != entity) {
            if (StringUtils.isNotEmpty(entity.getName())) {
                wrapper.like(DeviceType::getName, entity.getName());
            }
            if (StringUtils.isNotEmpty(entity.getCode())) {
                wrapper.like(DeviceType::getCode, entity.getCode());
            }
        }
        return wrapper;
    }

    /**
     * 结果封装
     * @param list
     * @return
     */
    private List<DeviceType> packList(List<DeviceType> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(entity -> {
                if (null != entity.getDeptId()) {
                    SysDept dept = deptService.selectDeptById(entity.getDeptId());
                    if (null != dept) {
                        entity.setDeptName(dept.getDeptName());
                    }
                }
            });
        }
        return list;
    }

}
